package integerTree;

public class Node {
    private Node leftChild = null;
    private Node rightChild = null;
    private int nodeValue;

    public Node(int nodeValue) {
        this.nodeValue = nodeValue;
    }

    public Node getLeftChild() {
        return leftChild;
    }

    public void setLeftChild(Node leftChild) {
        this.leftChild = leftChild;
    }

    public Node getRightChild() {
        return rightChild;
    }

    public void setRightChild(Node rightChild) {
        this.rightChild = rightChild;
    }

    public int getNodeValue() {
        return nodeValue;
    }

    private int minValue() {
        if (leftChild == null)
            return nodeValue;
        else
            return leftChild.minValue();
    }

    public boolean remove(Node parentNode, int nodeValue) {
        if (parentNode != null) {
            if (nodeValue < this.nodeValue) {
                if (leftChild != null)
                    return leftChild.remove(this, nodeValue);
                else
                    return false;
            } else if (nodeValue > this.nodeValue) {
                if (rightChild != null)
                    return rightChild.remove(this, nodeValue);
                else
                    return false;
            } else {
                if (leftChild != null && rightChild != null) {
                    this.nodeValue = rightChild.minValue();
                    rightChild.remove(this, this.nodeValue);
                } else if (parentNode.leftChild == this) {
                    parentNode.leftChild = (leftChild != null) ? leftChild : rightChild;
                } else if (parentNode.rightChild == this) {
                    parentNode.rightChild = (leftChild != null) ? leftChild : rightChild;
                }
                return true;
            }
        }
        return false;
    }
}
